# coding: utf-8
import os
import json
import urllib
from datetime import datetime

from math import floor

from common.bid_notify.utils import get_demand_info
from common.models import model_factory, FeedbackStatus, DemandStatus, Feedback


class WXContent(object):
    """
    create by ld_wu 2018-03-13

    """

    @classmethod
    def recharge_content(cls, session, demand, user, pack):
        wx_template = model_factory.wechat_template.get_by_args(
            session,
            code='demand_recharge_notify'
        )
        template_id = wx_template.template_code
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        demand_url = urllib.parse.urljoin(
            host, '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
        )
        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        msg = (
            """您竞拍的{city}{cate}订单已中标，因您剩余汇币不足，无法完成支付，立即充值联系客户\n""".format(
                city=demand.city,
                cate=demand.cate_display
            )
        )

        template_data = {
            'openid': user.wx_openid,
            'template_id': template_id,
            'data': {
                "first": {
                    "value": msg,
                    "color": "#173177"
                },
                "keyword1": {
                    'value': '{}'.format(user.mobile),
                    "color": "#173177"
                },
                "keyword2": {
                    "value": "{}汇币".format(pack.bid_point),
                    "color": "#173177"
                },
                "remark": {
                    "value": "\n速戳充值联系客户↓↓↓",
                    "color": "#4785F9"
                }
            },
            'url': demand_url
        }

        return template_data

    @classmethod
    def follow_content(cls, session, demand, user):
        """
        create by ld_wu 2018-01-26
        :return:
        """
        wx_template = model_factory.wechat_template.get_by_args(
            session,
            code='demand_winner_notify'
        )
        template_id = wx_template.template_code
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        if demand.status in (
            DemandStatus.DISPATCHING.value,
            DemandStatus.MASTER_DISPATCHING.value
        ):
            demand_url = urllib.parse.urljoin(
                host,
                '#DispatchDemand?did={d_id}&login_bind=1'.format(d_id=demand.id)
            )
        else:
            demand_url = urllib.parse.urljoin(
                host,
                '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
            )
        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        msg = (
            """您已获取客户联系方式，如需锁定或取消跟进, 请及时反馈！\n"""
        )

        published_date = datetime.fromtimestamp(demand.published_at).strftime(
            '%F')

        demand_info = """{cate}订单、{surr}、{size}{color}{span}"""

        demand_info = demand_info.format(
            cate=demand.cate_display,
            surr=demand.surr_display,
            size=(str(demand.size) + '㎡、') if demand.size else '',
            color=demand.color_display,
            span=('、' + str(demand.span)) if demand.span else ''
        )

        template_data = {
            'openid': user.wx_openid,
            'template_id': template_id,
            'data': {
                "first": {
                    "value": msg,
                    "color": "#173177"
                },
                "keyword1": {
                    'value': '{}'.format(published_date),
                    "color": "#173177"
                },
                "keyword2": {
                    "value": "{prov}{city}{address}".format(
                        prov=demand.prov,
                        city=demand.city,
                        address=(demand.addr or '')
                    ),
                    "color": "#173177"
                },
                "keyword3": {
                    "value": demand_info,
                    "color": "#173177"
                },
                "remark": {
                    "value": "\n速戳订单进行“锁定”或“退款”↓↓↓",
                    "color": "#4785F9"
                }
            },
            'url': demand_url
        }

        return template_data

    @classmethod
    def approval_content(cls, session, demand, user, partic, add_point=0):
        """
        create by ld_wu 2018-01-26
        :return:
        """
        wx_template = model_factory.wechat_template.get_by_args(
            session,
            code='finish_img_notify'
        )
        template_id = wx_template.template_code
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        demand_url = urllib.parse.urljoin(
            host,
            '#DemandDetail?did={d_id}&login_bind=1'.format(
                d_id=demand.id)
        )
        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        approve_status = (
            '通过' if partic.feedback_status == FeedbackStatus.PASS.value
            else '不通过'
        )
        msg = (
            """您反馈的信息审核{}\n""".format(approve_status)
        )

        demand_info = '{prov}{city}{type}{cate}项目{feedback}'.format(
            prov=demand.prov,
            city=demand.city,
            type=demand.type_display,
            cate=demand.cate_display,
            feedback=', {}'.format(
                Feedback(partic.feedback).display
            ) if partic.feedback else ''
        )

        if partic.feedback_status == FeedbackStatus.PASS.value:
            if partic.demand_status not in (
                DemandStatus.DISPATCHING.value,
                DemandStatus.MASTER_DISPATCHING.value
            ):
                remark = '\n{}个汇币已返还，可在您的账户中查看，点击查看详情↓↓↓'.format(
                        int(add_point)
                    )
            else:
                remark = '\n已返还1次派单次数，可在您的账户中查看，点击查看详情↓↓↓'
        else:
            remark = '\n点击查看项目详细↓↓↓'

        template_data = {
            'openid': user.wx_openid,
            'template_id': template_id,
            'data': {
                "first": {
                    "value": msg,
                    "color": "#173177"
                },
                "keyword1": {
                    'value': demand_info,
                    "color": "#173177"
                },
                "keyword2": {
                    "value": '审核{}{}'.format(
                        approve_status,
                        '' if not partic.feedback_refuse_content else ', {}'.format(
                            partic.feedback_refuse_content
                        )
                    ),
                    "color": "#173177"
                },
                "remark": {
                    "value": remark,
                    "color": "#4785F9"
                }
            },
            'url': demand_url
        }

        return template_data

    @classmethod
    def winner_content(cls, session, demand, user, partic):
        """
        create by ld_wu 2018-01-26
        :return:
        """
        wx_template = model_factory.wechat_template.get_by_args(
            session,
            code='bid_success_notify'
        )
        template_id = wx_template.template_code
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        demand_url = urllib.parse.urljoin(
            host,
            '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
        )
        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        punish_point = floor(float(partic.offer) * 0.3) or 1
        if not partic.voucher_id:
            msg = (
                """已获取客户联系方式，请在10分钟内联系，逾期名额作废并扣除{}个（30%）汇币\n""".format(punish_point)
            )
        else:
            msg = (
                """请在10分钟内联系客户，超时未联系号码失效！另：代金券不支持退返。"""
            )

        demand_info = """{city}-LED显示屏{cate}""".format(
            cate=demand.cate_display,
            city=demand.city
        )

        template_data = {
            'openid': user.wx_openid,
            'template_id': template_id,
            'data': {
                "first": {
                    "value": msg,
                    "color": "#173177"
                },
                "keyword1": {
                    'value': demand_info,
                    "color": "#173177"
                },
                "keyword2": {
                    'value': '{}汇币'.format(partic.offer) if not partic.voucher_id else '已使用代金券支付',
                    "color": "#173177"
                },
                "keyword3": {
                    "value": '10分钟后',
                    "color": "#173177"
                },
                "remark": {
                    "value": "\n速戳联系客户↓↓↓",
                    "color": "#4785F9"
                }
            },
            'url': demand_url
        }

        return template_data

    @classmethod
    def new_order_content(cls, session, demand, for_training=False):
        """
        created by chenhj at 2017/7/26

        """

        def generate_remark_value():
            """
            create by zhouhl 2017-12-27
            生成推送消息的备注部分，需要包含客户要求和发布理由
            """
            remark = ''
            published_count = demand.published_count
            if published_count > 1:
                publish_remark = json.loads(demand.publish_remark)
                for count in range(published_count, 1, -1):
                    count_remark = publish_remark.get(str(count), '')
                    if count_remark:
                        tmp_remark = '【{count}次发布】{count_remark}\n'.format(
                            count=count,
                            count_remark=count_remark
                        )
                        remark += tmp_remark
            remark += '【首发】' + demand.remark if demand.remark else ''
            return remark

        t = model_factory.wechat_template.get_by_args(session, code='new_order')
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        first_value = '{prov}{city}有客户要{cate}LED显示屏'.format(
            prov=demand.prov, city=demand.city, cate=demand.cate_display
        )
        if for_training:
            remark_value = ''
            first_value = '【赠送】{}'.format(first_value)
            first_color = '#f4c042'
            demand_url = urllib.parse.urljoin(
                host,
                '#DispatchDemand?did={d_id}&login_bind=1'.format(d_id=demand.id)
            )
        else:
            remark_value = '\n支持24小时无理由退款\n\n备注：\n%s' % (
                generate_remark_value())
            if demand.status in (
                DemandStatus.DISPATCHING.value,
                DemandStatus.MASTER_DISPATCHING.value
            ):
                first_value = '【派单尊享】{}'.format(first_value)
                first_color = '#18AF6F'
                demand_url = urllib.parse.urljoin(
                    host,
                    '#DispatchDemand?did={d_id}&login_bind=1'.format(d_id=demand.id)
                )
            elif demand.status == DemandStatus.BRONZE_MEDAL_DISCOUNT.value:
                first_value = '【优先抢单】{}'.format(first_value)
                first_color = '#F5A623'
                demand_url = urllib.parse.urljoin(
                    host,
                    '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
                )
            else:
                first_color = '#173177'
                demand_url = urllib.parse.urljoin(
                    host,
                    '#DemandDetail?did={d_id}&login_bind=1'.format(
                        d_id=demand.id
                    )
                )

        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        data = t.content.replace(
            'first_value', first_value
        ).replace(
            'keyword1_value', 'LED显示屏{cate}'.format(cate=demand.cate_display)
        ).replace(
            'keyword2_value',
            datetime.fromtimestamp(demand.published_at).strftime('%F %T')
        ).replace(
            'keyword3_value', '议价' if not demand.budget else str(demand.budget)
        ).replace(
            'keyword4_value', '{surr}{size}{color}{span}'.format(
                surr=str(demand.surr_display),
                size=('、' + str(demand.size) + '㎡') if demand.size else '',
                color=('、' + str(demand.color_display)),
                span=('、' + str(demand.span)) if demand.span else '',
            )
        ).replace(
            'remark_value', json.dumps(
                remark_value, ensure_ascii=False
            )
        ).replace('first_color_value', first_color)

        demand_info = get_demand_info(demand)

        if demand_info:
            demand_info += '，'

        return t.template_code, json.loads(
            data), demand_url, demand.cate_display, demand_info
    
    @classmethod
    def timeout_payback_content(cls, session, demand, user, ret_bid_point):
        """
        created by chenhj at 2018/6/11

        """
        wx_template = model_factory.wechat_template.get_by_args(
            session,
            code='timeout_payback'
        )
        template_id = wx_template.template_code
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        owner = model_factory.user.get_by_id(session, demand.uid)

        if demand.status in (
            DemandStatus.DISPATCHING.value,
            DemandStatus.MASTER_DISPATCHING.value
        ):
            demand_url = urllib.parse.urljoin(
                host,
                '#DispatchDemand?did={d_id}&login_bind=1'.format(d_id=demand.id)
            )
        else:
            demand_url = urllib.parse.urljoin(
                host,
                '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
            )
        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        data = wx_template.content.replace(
            'first_value', '{}{}{}㎡, {}, {}LED屏{}订单超时未联系, 系统自动退还{}(70%)汇币'.format(
                demand.city, owner.nickname, demand.size, demand.span,
                demand.surr_display, demand.cate_display, ret_bid_point
            )
        ).replace(
            'refund_value', '{}汇币'.format(ret_bid_point)
        ).replace(
            'reason_value', '订单超时未联系'
        )

        return {
            'openid': user.wx_openid,
            'template_id': template_id,
            'data': json.loads(data),
            'url': demand_url
        }

    @classmethod
    def bid_winner_notify_content(cls, session, partic, user):
        """
        created by chenhj at 2018/6/12
        提醒工程商及时联系客户
        """
        wx_template = model_factory.wechat_template.get_by_args(
            session,
            code='bid_success_notify'
        )
        template_id = wx_template.template_code
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        demand = model_factory.demand.get_by_id(session, partic.demand_id)

        if demand.status in (
            DemandStatus.DISPATCHING.value,
            DemandStatus.MASTER_DISPATCHING.value
        ):
            demand_url = urllib.parse.urljoin(
                host,
                '#DispatchDemand?did={d_id}&login_bind=1'.format(d_id=demand.id)
            )
        else:
            demand_url = urllib.parse.urljoin(
                host,
                '#DemandDetail?did={d_id}&login_bind=1'.format(d_id=demand.id)
            )
        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        punish_point = floor(float(partic.offer) * 0.3) or 1
        if not partic.voucher_id:
            msg = (
                """您的订单还剩5分钟超时, 请尽快联系！超时号码失效, 且扣除{}个（30%）汇币!\n""".format(punish_point)
            )
        else:
            msg = (
                """您的订单还剩5分钟超时，请尽快联系！超时号码失效！另：代金券不支持退返。"""
            )

        demand_info = """{city}-LED显示屏{cate}""".format(
            cate=demand.cate_display,
            city=demand.city
        )

        return {
            'openid': user.wx_openid,
            'template_id': template_id,
            'data': {
                "first": {
                    "value": msg,
                    "color": "#173177"
                },
                "keyword1": {
                    'value': demand_info,
                    "color": "#173177"
                },
                "keyword2": {
                    'value': '{}汇币'.format(partic.offer) if not partic.voucher_id else '已使用代金券支付',
                    "color": "#173177"
                },
                "keyword3": {
                    "value": '5分钟后',
                    "color": "#173177"
                },
                "remark": {
                    "value": "\n速戳联系客户↓↓↓",
                    "color": "#4785F9"
                }
            },
            'url': demand_url
        }

    @classmethod
    def lock_return_dispatch_content(cls, session, demand, user):
        """
        created by chenhj at 2018/6/11

        """
        wx_template = model_factory.wechat_template.get_by_args(
            session,
            code='timeout_payback'
        )
        template_id = wx_template.template_code
        host = os.environ.get('wph_host') or ''
        opc_host = os.environ.get('opc_host') or ''

        demand_url = urllib.parse.urljoin(
            host,
            '#DispatchDemand?did={d_id}&login_bind=1'.format(d_id=demand.id)
        )
        demand_url = '{host}?redirect_url={url}'.format(
            host=urllib.parse.urljoin(opc_host, 'api/Login/handleLogin4Wx'),
            url=urllib.parse.quote_plus(demand_url)
        )

        data = wx_template.content.replace(
            'first_value', '{}、{}㎡、{}、{}、{}屏订单被其他用户锁定, 系统自动退返您的派单点'.format(
                demand.city, demand.size, demand.span,
                demand.surr_display, demand.color_display
            )
        ).replace(
            'refund_value', '1个派单点'
        ).replace(
            'reason_value', '派送订单被其他用户锁定'
        )

        return {
            'openid': user.wx_openid,
            'template_id': template_id,
            'data': json.loads(data),
            'url': demand_url
        }
